#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <cstring>
#include "UdpServer.hpp"
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <cstring>

using namespace std;
const char *filename = "./chat.txt";

void Usage(string proc)
{
    cout << "Usage: " << proc << "+ip+port" << endl;
}

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(0);
    }
    string serverip = argv[1];
    uint16_t serverport = stoi(argv[2]);

    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd < 0)
    {
        cerr << "socket create error" << endl;
        exit(1);
    }
    cout << "socket create success" << endl;

    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(serverport);
    server.sin_addr.s_addr = INADDR_ANY;

    while (true)
    {
        cout << "Please message# ";
        string message;
        getline(cin, message);
        ssize_t s = sendto(sockfd, message.c_str(), message.size(), 0, (struct sockaddr *)&server, sizeof(server));
        if (s > 0)
        {
            int fd = open(filename, O_WRONLY | O_APPEND);
            if (fd < 0)
            {
                cerr << "file open error" << endl;
                exit(0);
            }

            char buffer[1024];
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            ssize_t r = recvfrom(sockfd, buffer, sizeof(buffer) - 1, 0, (struct sockaddr *)&peer, &len);
            if (r > 0)
            {
                buffer[r] = 0;
                write(fd, buffer, strlen(buffer));
            }
            else
            {
                break;
            }
        }
        else
        {
            break;
        }
    }

    return 0;
}